<?php

namespace App\Controller;

use App\JsonRPC\Error;
use App\JsonRPC\InvalidPayloadException;
use App\JsonRPC\Response;
use Psr\Http\Message\ServerRequestInterface;
use Spiral\Prototype\Traits\PrototypeTrait;

class JsonRpcController
{
    use PrototypeTrait;

    /**
     * @return array
     */
    public function index(ServerRequestInterface $serverRequest)
    {
        $procedures = $this->jsonrpc->extractProcedureFromRequest($serverRequest);

        /** @var Response[] $responses */
        $responses = [];
        foreach ($procedures as $procedure) {
            try {
                $tmp = $procedure->execute();
                $responses[] = Response::createFromResult($procedure, $tmp);
            } catch (Error $e) {
                $responses[] = Response::createFromError($procedure, $e);
            } catch (InvalidPayloadException $e) {
                $responses[] = Response::createFromException($procedure, $e);
            }
        }

        if (count($responses) === 1) {
            return array_shift($responses)->toArray();
        }

        $result = [];
        foreach ($responses as $response) {
            $result[] = $response->toArray();
        }
        return $result;
    }
}
